<template>
	<div class="max_box">
		<!-- 用于合成图片的隐藏canvas -->
		<canvas 
			canvas-id="saveCanvas" 
			style="position: absolute; left: -9999px; width: 375px; height: 812px;"
			:style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}"
		></canvas>
		
		<div style="width: 100%; display: flex; justify-content: center;">
			<div class="canvas_class">
				<canvas class="canvas_classs" canvas-id="qrcodes" style="width: 100%; height: 100%;"></canvas>
			</div>
		</div>
		<div style="width: 100%; position: absolute; bottom: 50px; display: flex; justify-content: center; margin: 0 auto;">
			<button 
				style="width: 90%; height: 30px; border-radius: 10px; background-color: #fb6c10;
				margin-right: 20px; color: #fff; text-align: center; line-height: 30px;  margin: 0 auto;"
				@click="saveToAlbum"
				:loading="saving"
			>
				{{ saving ? '保存中...' : '保存相册' }}
			</button>
			<!-- <button 
				style="width: 150px; height: 30px; border-radius: 10px; background-color: #F9AE3D; 
				margin-left: 20px; color: #fff; text-align: center; line-height: 30px;" 
				open-type="share"
			>
				分 享
			</button> -->
		</div>
	</div>
</template>

<script>
import QRCode from "../../utils/qrcode.js"
export default {
	data() {
		return {
			saving: false, // 保存状态
			canvasWidth: 375, // 画布宽度
			canvasHeight: 812, // 画布高度
			backgroundImageUrl: 'https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/05/22/qq_20250522114935A207.jpg'
		}
	},
	onShareAppMessage(res) {
		console.log(res)
		return {
			title: '注册即得200补贴!',
			path: '/pages_h5/index/index?shareId=' + uni.getStorageSync('merId'),
			// imageUrl: '/static/share.png'
		};
	},
	onShareTimeline() {
		return {
			title: '智享优圈',
			query: 'id=123',
			imageUrl: '/pages_h5/myCenter/index?id=' + uni.getStorageSync('merId')
		};
	},

	mounted() {
		// 获取系统信息，设置画布尺寸
		this.getSystemInfo();
		
		var uid = uni.getStorageSync('merId')
		this.$nextTick(() => {
			try {
				var qrText = 'https://www.wantongkonggu.cn/adminMgrh7/smallCenter/' + uid + "-1"
				let qrcode = new QRCode({
					text: qrText, // 动态生成的二维码内容
					canvasId: 'qrcodes',
					width: 180, // 设置二维码的宽度
					height: 180, // 设置二维码的高度
					size: 180,
					foreground: '#000000',
					background: '#fff',
					correctLevel: 3
				});
			} catch (error) {
				console.error('设置QRCode时出错:', error);
			}
		})
	},
	methods: {
		// 获取系统信息，设置画布尺寸
		getSystemInfo() {
			const systemInfo = uni.getSystemInfoSync();
			this.canvasWidth = systemInfo.windowWidth || 375;
			this.canvasHeight = systemInfo.windowHeight || 812;
		},

		// 保存到相册的主方法
		async saveToAlbum() {
			if (this.saving) return; // 防止重复点击
			
			this.saving = true;
			
			try {
				// 1. 检查授权状态
				await this.checkWritePhotosAlbumAuth();
				
				// 2. 合成图片
				const tempFilePath = await this.createCompositeImage();
				
				// 3. 保存到相册
				await this.saveImageToPhotosAlbum(tempFilePath);
				
				// 4. 显示成功提示
				uni.showToast({
					title: '保存成功',
					icon: 'success',
					duration: 2000
				});
				
			} catch (error) {
				console.error('保存失败:', error);
				uni.showToast({
					title: error.message || '保存失败',
					icon: 'none',
					duration: 2000
				});
			} finally {
				this.saving = false;
			}
		},

		// 检查相册写入权限
		checkWritePhotosAlbumAuth() {
			return new Promise((resolve, reject) => {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.writePhotosAlbum']) {
							// 已授权
							resolve();
						} else if (res.authSetting['scope.writePhotosAlbum'] === false) {
							// 用户拒绝过，需要引导用户去设置页面
							uni.showModal({
								title: '提示',
								content: '需要您授权保存相册权限，请在设置中开启',
								confirmText: '去设置',
								success: (modalRes) => {
									if (modalRes.confirm) {
										uni.openSetting({
											success: (settingRes) => {
												if (settingRes.authSetting['scope.writePhotosAlbum']) {
													resolve();
												} else {
													reject(new Error('未获得相册权限'));
												}
											},
											fail: () => {
												reject(new Error('打开设置失败'));
											}
										});
									} else {
										reject(new Error('用户取消授权'));
									}
								}
							});
						} else {
							// 首次申请权限
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									resolve();
								},
								fail: () => {
									reject(new Error('获取相册权限失败'));
								}
							});
						}
					},
					fail: () => {
						reject(new Error('获取授权信息失败'));
					}
				});
			});
		},

		// 创建合成图片
		createCompositeImage() {
			return new Promise((resolve, reject) => {
				// 1. 先下载背景图片
				this.downloadBackgroundImage()
					.then((backgroundTempPath) => {
						const ctx = uni.createCanvasContext('saveCanvas', this);
						
						// 2. 绘制背景图片（使用临时文件路径）
						ctx.drawImage(
							backgroundTempPath,
							0, 0,
							this.canvasWidth, this.canvasHeight
						);
						
						// 3. 等待背景图片绘制完成后，获取二维码并绘制
						setTimeout(() => {
							// 获取二维码临时图片
							this.getQRCodeTempImage()
								.then((qrcodeTempPath) => {
									// 计算二维码在合成图片中的位置（与原布局保持一致）
									const qrcodeX = (this.canvasWidth - 230) / 2; // 考虑边框和padding
									const qrcodeY = this.canvasHeight - 300; // 距离底部位置
									
									// 先绘制二维码背景（白色边框）
									ctx.setFillStyle('#ffffff');
									ctx.fillRect(qrcodeX, qrcodeY, 230, 230);
									
									// 绘制蓝色边框
									ctx.setStrokeStyle('#3C9CFF');
									ctx.setLineWidth(4);
									ctx.strokeRect(qrcodeX, qrcodeY, 230, 230);
									
									// 绘制二维码
									ctx.drawImage(
										qrcodeTempPath,
										qrcodeX + 15, qrcodeY + 15,
										200, 200
									);
									
									// 绘制完成，导出图片
									ctx.draw(false, () => {
										setTimeout(() => {
											uni.canvasToTempFilePath({
												canvasId: 'saveCanvas',
												success: (res) => {
													resolve(res.tempFilePath);
												},
												fail: (error) => {
													console.error('导出图片失败:', error);
													reject(new Error('生成图片失败'));
												}
											}, this);
										}, 500);
									});
								})
								.catch((error) => {
									reject(error);
								});
						}, 500);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},

		// 下载背景图片到临时文件
		downloadBackgroundImage() {
			return new Promise((resolve, reject) => {
				uni.downloadFile({
					url: this.backgroundImageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('背景图片下载成功:', res.tempFilePath);
							resolve(res.tempFilePath);
						} else {
							reject(new Error('背景图片下载失败'));
						}
					},
					fail: (error) => {
						console.error('背景图片下载失败:', error);
						reject(new Error('背景图片下载失败'));
					}
				});
			});
		},

		// 获取二维码临时图片
		getQRCodeTempImage() {
			return new Promise((resolve, reject) => {
				uni.canvasToTempFilePath({
					canvasId: 'qrcodes',
					success: (res) => {
						console.log('二维码临时图片生成成功:', res.tempFilePath);
						resolve(res.tempFilePath);
					},
					fail: (error) => {
						console.error('二维码临时图片生成失败:', error);
						reject(new Error('获取二维码失败'));
					}
				}, this);
			});
		},

		// 保存图片到相册
		saveImageToPhotosAlbum(tempFilePath) {
			return new Promise((resolve, reject) => {
				uni.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						resolve();
					},
					fail: (error) => {
						console.error('保存到相册失败:', error);
						reject(new Error('保存到相册失败'));
					}
				});
			});
		}
	}
}
</script>

<style>
page {
	width: 100%;
	height: 100%;
}

.max_box {
	width: 100%;
	height: 100%;
	background-image: url('https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/05/22/qq_20250522114935A207.jpg');
	background-repeat: no-repeat;
	background-size: 100% 100%;
}

.canvas_class {
	position: absolute;
	bottom: 100px;
	padding: 15px;
	width: 180px;
	height: 180px;
	border: 2px solid #3C9CFF;
	border-radius: 15px;
	background-color: #fff;
}

/* .canvas_classs {
		padding: 15px;
	} */
</style>